import onload from "../utils/onload";
import tracker from "../utils/tracker";
import getSelector from "../utils/getSelector";
import getLastEvent from "../utils/getLastEvent";

export function timing() {
  let FMP, LCP;

  new PerformanceObserver((entryList, observer) => {
    const entries = entryList.getEntries();
    FMP = entries[0];
    observer.disconnect(); // 只观察一次
  }).observe({ entryTypes: ["element"] }); // 观察页面中有意义的元素

  new PerformanceObserver((entryList, observer) => {
    const entries = entryList.getEntries();
    LCP = entries[0];
    observer.disconnect();
  }).observe({ entryTypes: ["largest-contentful-paint"] }); // 观察最大内容绘制

  new PerformanceObserver((entryList, observer) => {
    let lastEvent = getLastEvent(); // 最后一个交互事件
    let firstInput = entryList.getEntries()[0];
    console.log("FID", firstInput);
    if (firstInput) {
      let inputDelay = firstInput.processingStart - firstInput.startTime;
      let duration = firstInput.duration;
      if (inputDelay > 0 || duration > 0) {
        tracker.send({
          kind: "experience",
          type: "firstInput",
          inputDelay,
          duration,
          startTime: firstInput.startTime,
          selector: lastEvent
            ? getSelector(lastEvent.path || lastEvent.target)
            : "", // 最后一个交互事件的元素});
        });
      }
    }
    observer.disconnect();
  }).observe({ type: "first-input", buffered: true }); // 观察首次输入延迟
  onload(function () {
    setTimeout(function () {
      const {
        connectStart,
        fetchStart,
        connectEnd,
        requestStart,
        responseStart,
        responseEnd,
        domInteractive,
        domContentLoadedEventStart,
        domContentLoadedEventEnd,
        loadEventStart,
        loadEventEnd,
        domLoading,
      } = performance.timing;
      tracker.send({
        type: "timing", // 统计每个阶段的时间
        kind: "experience", // 用户体验指标
        connectTime: connectEnd - connectStart, // 连接时间
        ttfbTime: responseStart - requestStart, // 首字节到达时间
        responseTime: responseEnd - responseStart, // 响应时间
        parseDOMTime: loadEventEnd - domLoading, // DOM解析时间
        domContentLoadedTime:
          domContentLoadedEventEnd - domContentLoadedEventStart, // DOMContentLoaded时间
        timeToInteractive: domInteractive - fetchStart, // 完整的加载时间
      });
      let FP = performance.getEntriesByName("first-paint")[0];
      let FCP = performance.getEntriesByName("first-contentful-paint")[0];
      console.log("FP", FP);
      console.log("FCP", FCP);
      console.log("FMP", FMP);
      console.log("LCP", LCP);
      tracker.send({
        kind: "experience",
        type: "paint",
        firstPaint: FP.startTime,
        firstContentfulPaint: FCP.startTime,
        firstMeaningfulPaint: FMP.startTime,
        LargestContentfulPaint: LCP.startTime,
      });
    }, 3000);
  });
}
